package com.sun.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;
import com.sun.pojo.Role;
import com.sun.pojo.User;
import com.sun.service.role.RoleServiceImol;
import com.sun.service.user.UserService;
import com.sun.service.user.UserServiceImpl;
import com.sun.util.Constants;
import com.sun.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Sun
 * @Date 2020/4/25 22:58
 * @Version 1.0
 */
//实现servlet复用
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String method = req.getParameter("method");

        if (method != null && method.equals("savepwd")) {
            this.updatepwd(req, resp);
        } else if (method != null && method.equals("pwdmodify")) {
            this.pwdModif(req, resp);
        } else if (method != null && method.equals("query")) {
            this.query(req, resp);
        }else if(method != null && method.equals("add")){
            this.add(req,resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    //修改密码
    public void updatepwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从session里获取用户对象
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");
        boolean flag = false;

        if (user != null && newpassword != null) {
            UserService userService = new UserServiceImpl();//调用业务层
            flag = userService.updatepwd(user.getId(), newpassword);

            if (flag) {
                req.setAttribute("message", "密码修改成功，请重新登陆");
                req.getSession().removeAttribute(Constants.USER_SESSION);//移除session
            } else {
                req.setAttribute("message", "密码修改失败");
            }

        } else {
            req.setAttribute("message", "新密码有问题");
        }

        req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
    }

    //验证旧密码，旧密码存在session中，不需要从数据库中查询
    public void pwdModif(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        String userPassword = user.getUserPassword();//存在Session中用户的旧密码
        String oldpassword = req.getParameter("oldpassword");//前端输入的旧密码

        Map<String, String> resultMap = new HashMap<String, String>();//结果集

        if (user == null) {//session失效（过期）
            resultMap.put("result", "sessionerror");
        } else if (StringUtils.isNullOrEmpty(oldpassword)) {
            resultMap.put("result", "error");
        } else {
            if (userPassword.equals(oldpassword)) {
                resultMap.put("result", "true");
            } else {
                resultMap.put("result", "false");
            }
        }

        resp.setContentType("application/json");//设置响应内容类型的应用为json格式
        PrintWriter writer = resp.getWriter();
        //JSONArray，阿里巴巴的工具类，转换格式
        writer.write(JSONArray.toJSONString(resultMap));//将map对象转换成json字符串，向外写出

        writer.flush();
        writer.close();
    }

    //进入用户管理页面，查询用户列表
    public void query(HttpServletRequest req, HttpServletResponse resp) {

        //从前端获取数据
        String queryUserName = req.getParameter("queryUserName");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryRole = 0;// 角色编号
        UserServiceImpl userService = new UserServiceImpl();//用来获取用户列表
        RoleServiceImol roleService = new RoleServiceImol();//用来获取角色列表

        int pageSize = 5;// 用户列表显示五行，页面容量固定
        int currentPageNo = 1; //第一次走这个请求，一定是第一页

        if (queryUserName == null) {
            queryUserName = "";
        }
        if (temp != null && !temp.equals("")) {
            queryRole = Integer.parseInt(temp);//给角色编号赋值：1 2 3
        }
        if (pageIndex != null) {
            currentPageNo = Integer.parseInt(pageIndex);// 给当前页赋值前端传来的页面下标
        }

        //查询用户总数(分页，上一页、下一页的情况)
        int totalCount = userService.getUserCount(queryUserName, queryRole);
        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = pageSupport.getTotalPageCount();//总共页数

        //控制首页和尾页
        if (currentPageNo < 1) {
            currentPageNo = 1;      //如果页面小于1，就显示第一页的东西
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;// 当前页面大于最后一页，就显示最后一页
        }

        List<User> userList = userService.getUserList(queryUserName, queryRole, currentPageNo, pageSize);// 获取用户列表
        List<Role> roleList = roleService.getRoleList();// 获取角色列表

        req.setAttribute("userList", userList);
        req.setAttribute("roleList", roleList);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("queryUserName", queryUserName);
        req.setAttribute("queryUserRole", queryRole);

        //返回到前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //添加用户
    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取前端输入的用户信息
        String id = req.getParameter("userID");
        String userName = req.getParameter("userName");
        String userRole = req.getParameter("userRole");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");

        User user = new User();
        //注意：前端传入的数据到后台都是字符串格式，set的时候要进行格式转换
        user.setId(Integer.valueOf(id));
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setUserRole(Integer.valueOf(userRole));
        user.setGender(Integer.valueOf(gender));
        user.setAddress(address);
        user.setPhone(phone);
        user.setModifyDate(new Date());
        user.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());//获取当前登陆对象的ID，就算更新者的ID
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));//通过日期格式对象，将字符串的日期转为Date类型
        } catch (ParseException e) {
            e.printStackTrace();
        }

        UserServiceImpl userService = new UserServiceImpl();

        boolean addUser = userService.addUser(user);

        if(addUser){
            resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
        }else {
            req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
        }


    }
}
